package com.bankwel.j2d.model;

public class MechanicalObject extends Object2d {

	private Vector2d vel;
	private Vector2d acc;
	private float mass;
	private float dt;

	public MechanicalObject() {
		super(0, 0);
		// TODO
		vel = new Vector2d();
		acc = new Vector2d();
		mass = 1f;
		dt = 0.01f;
	}

	public Vector2d getVel() {
		return vel;
	}

	public void setVel(Vector2d vel) {
		this.vel = vel;
	}

	public Vector2d getAcc() {
		return acc;
	}

	public void setAcc(Vector2d acc) {
		this.acc = acc;
	}

	public float getMass() {
		return mass;
	}

	public void setMass(float mass) {
		this.mass = mass;
	}

	public float getDt() {
		return dt;
	}

	public void setDt(float dt) {
		this.dt = dt;
	}

	/*************************************/
	public void motion(Vector2d force) {
		if (force == null) {
			force = new Vector2d(0, 0);
		}
		acc.set(force.getX() / mass, force.getY() / mass);
		float vx = vel.getX();
		float vy = vel.getY();
		float ax = acc.getX();
		float ay = acc.getY();

		getRef().plus(vx * dt, vy * dt);
		getRef().plus(ax * dt, ay * dt);
	}

	public boolean restrainIn(float x1, float x2, float y1, float y2) {
		float px = getRef().getX();
		float vx = vel.getX();
		if ((px < x1 && vx < 0) || (px > x2 && vx > 0)) {
			vel.setX(-vx);
			return true;
		}
		float py = getRef().getY();
		float vy = vel.getY();
		// The object is out of boundry and tend to out more
		if ((py < y1 && vy < 0) || (py > y2 && vy > 0)) {
			vel.setY(-vy);
			return true;
		}
		return false;
	}

	/***************************************/
	@Override
	public String toString() {
		StringBuffer sb = new StringBuffer();
		sb.append("[position:");
		sb.append(getRef().toString());
		sb.append(";velocity:");
		sb.append(vel.toString());
		sb.append(";acceleration:");
		sb.append(acc.toString());
		sb.append(";mass:");
		sb.append(mass);
		sb.append(";speed:");
		sb.append(vel.norm());
		sb.append("]");
		return sb.toString();
	}

}
